package io.xxx.xbutler.core.callback;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.hy.corecode.idgen.WFGIdGenerator;
import io.xxx.xbutler.data.ContactMapper;
import io.xxx.xbutler.data.RoomContactMapper;
import io.xxx.xbutler.domain.Callback;
import io.xxx.xbutler.domain.Contact;
import io.xxx.xbutler.domain.RoomContact;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 群成员信息列表回调
 * <p>
 * 商家通过调用群成员信息列表接口之后，可以通过"群成员信息列表回调接口"直接返回给商家群成员信息。群成员排序为随机排序。
 *
 * <pre>
 *{
 *     "Data": {
 *         "Members": [
 *             {
 *                 "vcNickName": "꧁༺月亮༻꧂🌜",
 *                 "vcFatherWxId": "wxid_70jt05y6clpq22",
 *                 "vcHeadImgUrl": "https://wx.qlogo.cn/mmhead/ver_1/hOY57fTMyLaMQsGjw1usljWg2iamhBic6a6xrHSkUQQcI0USVePHJFZJ0Ns8aqJWKnEIkmnW6fpQadibPIcoict3KViazxTDhnBjawuX6RsiabzPyJ8HloF2aCibEy2FUvDhqBC/132",
 *                 "vcGroupNickName": "",
 *                 "vcBase64NickName": "6qeB4Ly65pyI5Lqu4Ly76qeC8J+MnA==",
 *                 "vcMemberUserWxId": "limingyue1209",
 *                 "vcMemberUserSerialNo": "CFBAD2EAE0F2132A4C586EA3715596B3",
 *                 "vcBase64GroupNickName": "",
 *                 "vcFatherWxUserSerialNo": "55984829BEFE48B35DD35E560BD33C44"
 *             },
 *             {
 *                 "vcNickName": "Jillx71",
 *                 "vcFatherWxId": "wxid_70jt05y6clpq22",
 *                 "vcHeadImgUrl": "https://wx.qlogo.cn/mmhead/ver_1/CibDzjspgYBicO7jPblKlkrBicuz6P2lk91z98j2bq4KrCxibZww5IeNicYGGibvLlicUo4k3EV5W3iafQv2Lk85tVeD20icfXId11ibVctkS2Q1r5nrR0icnLTv1lQzpgQmJjEe8rL/132",
 *                 "vcGroupNickName": "",
 *                 "vcBase64NickName": "SmlsbHg3MQ==",
 *                 "vcMemberUserWxId": "wxid_d8zr1m5jugen21",
 *                 "vcMemberUserSerialNo": "F7DCBC9E93DA31CEA913607CA2EE3867",
 *                 "vcBase64GroupNickName": "",
 *                 "vcFatherWxUserSerialNo": "55984829BEFE48B35DD35E560BD33C44"
 *             },
 *             {
 *                 "vcNickName": "小兴测",
 *                 "vcFatherWxId": "wxid_70jt05y6clpq22",
 *                 "vcHeadImgUrl": "https://wx.qlogo.cn/mmhead/ver_1/n8JRTECsHfnaxFnJvPzmg0Wcby3DBHs0ibwAxVmxyYibpAicHz9NQz7I0pibNh1ntz5GYxyxnPbicPeQTWYbhRz41LvY0PSTqaXhIoJYVpib5ZhgWrGh1p8wNlKyyNnHrwAribhkmeOBDXvMSGia8Uh3OBQ47A/132",
 *                 "vcGroupNickName": "",
 *                 "vcBase64NickName": "5bCP5YW05rWL",
 *                 "vcMemberUserWxId": "wxid_9ybf2wcqev9q22",
 *                 "vcMemberUserSerialNo": "8B9CBF9043BCEBB9391768581ED5240D",
 *                 "vcBase64GroupNickName": "",
 *                 "vcFatherWxUserSerialNo": "55984829BEFE48B35DD35E560BD33C44"
 *             }
 *         ],
 *         "Managers": [
 *             {
 *                 "vcManagerWxId": "wxid_zfgdpkoqh5wi22",
 *                 "vcManagerSerialNo": "7E84B4D7E0126E2ACDC023A59A0B18D4"
 *             }
 *         ],
 *         "nMemberCount": 52,
 *         "vcChatRoomId": "56514793648@chatroom",
 *         "ChatAdminType": 0,
 *         "vcChatRoomName": "小助手测试群",
 *         "nChatRoomIsOpen": 1,
 *         "vcChatAdminWxId": "wxid_9ybf2wcqev9q22",
 *         "vcChatRoomSerialNo": "DE74ABB2CA5BF1BC921F838DCB1B0E47",
 *         "IsEnterpriseChatroom": false,
 *         "vcBase64ChatRoomName": "5bCP5Yqp5omL5rWL6K+V576k",
 *         "vcChatAdminWxUserSerialNo": "8B9CBF9043BCEBB9391768581ED5240D"
 *     },
 *     "nType": 4501,
 *     "nResult": 1,
 *     "vcResult": "SUCCESS",
 *     "nTimeStamp": 1739584544118,
 *     "vcSerialNo": "20250215095543570334310164791",
 *     "vcRobotWxId": "wxid_bysnjh4y1f1922",
 *     "vcMerchantNo": "202407150008480",
 *     "vcRobotSerialNo": "DA1B048A0F72A1142FE1F29C982E3B79"
 * }
 * </pre>
 */
@Slf4j
@Component
public class _4501Handler implements CallbackHandler {

    @Resource
    private WFGIdGenerator idGenerator;

    @Resource
    private ContactMapper contactMapper;

    @Resource
    private RoomContactMapper roomContactMapper;

    @Override
    public String name() {
        return "群成员信息列表回调";
    }

    @Override
    public boolean supports(int type) {
        return type == 4501;
    }

    @Override
    public void handle(Callback callback) {
        LocalDateTime now = LocalDateTime.now();
        JSONObject data = (JSONObject) callback.getData();
        String roomId = data.getString("vcChatRoomId");
        JSONArray members = data.getJSONArray("Members");
        for (Object o : members) {
            JSONObject member = JSONObject.from(o);
            String contactId = member.getString("vcMemberUserWxId");
            boolean contactExists = isExists(contactId);
            Contact contact = new Contact()
                    .setId(contactId)
                    .setSerialNo(member.getString("vcMemberUserSerialNo"))
                    .setName(member.getString("vcNickName"))
                    .setBase64Name(member.getString("vcBase64NickName"))
                    .setAvatar(member.getString("vcHeadImgUrl"))
                    .setUpdatedTime(now);
            if (!contactExists) {
                contact.setCreatedTime(now);
                contactMapper.insert(contact);
            } else {
                contactMapper.updateById(contact);
            }

            Set<String> managers = getManagers(data);

            boolean roomContactExists = isExists(roomId, contactId);
            if (!roomContactExists) {
                RoomContact roomContact = new RoomContact()
                        .setId(idGenerator.next())
                        .setRoomId(roomId)
                        .setRoomSerialNo(data.getString("vcChatRoomSerialNo"))
                        .setContactId(contactId)
                        .setContactSerialNo(member.getString("vcMemberUserSerialNo"))
                        .setContactName(member.getString("vcGroupNickName"))
                        .setBase64ContactName(member.getString("vcBase64GroupNickName"))
                        .setInventorId(member.getString("vcFatherWxId"))
                        .setInventorSerialNo(member.getString("vcFatherWxUserSerialNo"))
                        .setManager(false)
                        .setUpdatedTime(now)
                        .setUpdatedTime(now);
                if (managers.contains(contactId)) {
                    roomContact.setManager(true);
                }
                roomContactMapper.insert(roomContact);
            } else {
                LambdaUpdateWrapper<RoomContact> wrapper = new LambdaUpdateWrapper<RoomContact>()
                        .set(RoomContact::getContactName, member.getString("vcGroupNickName"))
                        .set(RoomContact::getBase64ContactName, member.getString("vcBase64GroupNickName"))
                        .set(RoomContact::getUpdatedTime, now)
                        .eq(RoomContact::getRoomId, roomId)
                        .eq(RoomContact::getContactId, contact.getId());
                if (managers.contains(contactId)) {
                    wrapper.set(RoomContact::getManager, true);
                } else {
                    wrapper.set(RoomContact::getManager, false);
                }
                roomContactMapper.update(wrapper);
            }
        }
    }

    private Set<String> getManagers(JSONObject data) {
        JSONArray managers = data.getJSONArray("Managers");
        if (ObjectUtils.isEmpty(managers)) {
            return Collections.emptySet();
        }
        return managers.stream()
                .map(it -> {
                    JSONObject manager = JSONObject.from(it);
                    return manager.getString("vcManagerWxId");
                })
                .collect(Collectors.toSet());
    }

    private boolean isExists(String contactId) {
        LambdaQueryWrapper<Contact> wrapper = new LambdaQueryWrapper<Contact>()
                .eq(Contact::getId, contactId);
        return contactMapper.exists(wrapper);
    }

    private boolean isExists(String roomId, String contactId) {
        LambdaQueryWrapper<RoomContact> wrapper = new LambdaQueryWrapper<RoomContact>()
                .eq(RoomContact::getRoomId, roomId)
                .eq(RoomContact::getContactId, contactId);
        return roomContactMapper.exists(wrapper);
    }
}
